package com.gxsyh.nantie.phone.consumer.controller;

import com.google.common.cache.Cache;
import com.gxsyh.nantie.commons.dto.PageHelpPhoneDTO;
import com.gxsyh.nantie.commons.dto.ResponseResult;
import com.gxsyh.nantie.commons.utils.OkHttpClientUtil;
import com.gxsyh.nantie.phone.consumer.configure.CacheConfiguration;
import com.gxsyh.nantie.phone.consumer.controller.dto.AddInformationParam;
import com.gxsyh.nantie.phone.consumer.controller.dto.UpdateInformationParam;
import com.gxsyh.nantie.phone.provider.api.TbInformationService;
import com.gxsyh.nantie.phone.provider.api.domain.TbHomeImg;
import com.gxsyh.nantie.phone.provider.api.domain.TbInformation;
import okhttp3.ResponseBody;
import org.apache.dubbo.config.annotation.Reference;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.redisson.codec.KryoCodec;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @email yom535@outlook.com
 * @author: 有民(yom535)
 * @date: 2020/2/12
 * @time: 16:03
 */
@RestController
public class InformationController {

    @Reference(version = "1.0.0")
    TbInformationService tbInformationService;

    @Value("${base.config.leaf.url}")
    String LEAF_URL;

    @Resource
    RedissonClient redissonClient;

    @Resource(name = "CacheCon")
    Cache cache;
    /**
     * 增加公告
     * @param addInformationParam 增加
     * @return 成功与否
     */
    @PostMapping(value = "/phone/add/information")
    public ResponseResult<Void> addInformation(@RequestBody AddInformationParam addInformationParam, HttpServletResponse response) throws IOException {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        TbInformation tbInformation=new TbInformation();

        ResponseBody body = OkHttpClientUtil.getInstance().getData(LEAF_URL + "log").body();
        Long id = Long.valueOf(body.string());

        tbInformation.setId(id);
        tbInformation.setTitle(addInformationParam.getTitle());
        tbInformation.setContent(addInformationParam.getContent());
        tbInformation.setUserId(Long.valueOf(authentication.getName()));
        tbInformation.setCreatetime(LocalDateTime.now());
        tbInformation.setUpdatetime(LocalDateTime.now());
        tbInformation.setSerialnum(999999L);


        int i = tbInformationService.addInformation(tbInformation);

        if (i>0){
            return new ResponseResult<>(HttpStatus.OK.value(),"增加公告成功",null);
        }
        else
        {
            response.setStatus(HttpStatus.BAD_REQUEST.value());
            return new ResponseResult<>(HttpStatus.BAD_REQUEST.value(),"增加失败请检查填写内容",null);
        }
    }

    /**
     *查询公告(三级缓存)
     * @param pagenum 页码
     * @return 分页的公告 每页5条
     */
    @GetMapping(value = "/phone/select/all/information")
    public ResponseResult<PageHelpPhoneDTO> selectAllInformation(@RequestParam int pagenum){
        //本地缓存
        PageHelpPhoneDTO cacheIfPresent = (PageHelpPhoneDTO) cache.getIfPresent("informationPage" + pagenum);
        if (cacheIfPresent!=null){
            return new ResponseResult<>(HttpStatus.OK.value(),"查询公告成功",cacheIfPresent);
        }
        //Redis缓存
        RBucket<PageHelpPhoneDTO> informationPage = redissonClient.getBucket("informationPage"+pagenum,new KryoCodec());
        PageHelpPhoneDTO informationPages = informationPage.get();
        if (informationPages==null){
//            查询数据库
            PageHelpPhoneDTO pageHelpPhoneDTO = tbInformationService.selectAllInformation(pagenum);
            informationPage.set(pageHelpPhoneDTO,10, TimeUnit.SECONDS);
            return new ResponseResult<>(HttpStatus.OK.value(),"查询公告成功",pageHelpPhoneDTO);
        }
        else
        {
//            Redis写进本地缓存
            cache.put("informationPage"+pagenum,informationPages);
            return new ResponseResult<>(HttpStatus.OK.value(),"查询公告成功",informationPages);
        }
    }

    /**
     *查询公告(无缓存主要是后台使用)
     * @param pagenum 页码
     * @return 分页的公告 每页5条
     */
    @GetMapping(value = "/phone/select/all/information/now")
    public ResponseResult<PageHelpPhoneDTO> selectAllInformationNow(@RequestParam int pagenum){
//            查询数据库
            PageHelpPhoneDTO pageHelpPhoneDTO = tbInformationService.selectAllInformation(pagenum);
            return new ResponseResult<>(HttpStatus.OK.value(),"查询公告成功",pageHelpPhoneDTO);
    }

    /**
     * 更新公告
     * @param updateInformationParam 通过ID 更新 标题 、 正文
     * @return 是否更新成功
     */
    @PostMapping(value = "/phone/update/information")
    public ResponseResult<Void> updateInformation(@RequestBody UpdateInformationParam updateInformationParam,HttpServletResponse response){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        TbInformation tbInformation=new TbInformation();
        tbInformation.setId(updateInformationParam.getId());
        tbInformation.setTitle(updateInformationParam.getTitle());
        tbInformation.setContent(updateInformationParam.getContent());
        tbInformation.setUserId(Long.valueOf(authentication.getName()));
        tbInformation.setUpdatetime(LocalDateTime.now());

        int i = tbInformationService.updateInformation(tbInformation);
        if (i>0){
            return new ResponseResult<>(HttpStatus.OK.value(),"更新公告成功",null);
        }
        else
        {
            response.setStatus(HttpStatus.BAD_REQUEST.value());
            return new ResponseResult<>(HttpStatus.BAD_REQUEST.value(),"更新失败请检查输入内容",null);
        }

    }

    /**
     *删除公告
     * @param informationid 通过公告的ID删除公告
     * @return 成功与否
     */
    @GetMapping(value = "/phone/delete/information")
    public ResponseResult<Void> deleteInformation(@RequestParam Long informationid)
    {
        int i = tbInformationService.deleteInformation(informationid);
        if (i>0){
            return new ResponseResult<>(HttpStatus.OK.value(),"删除成功",null);
        }
        else
        {
            return new ResponseResult<>(HttpStatus.BAD_REQUEST.value(),"删除失败，请重试",null);
        }
    }

    /**
     * 置顶公告
     * @param informationid 通过ID置顶某条公告
     * @return 成功与否
     */
    @GetMapping(value = "/phone/top/information")
    public ResponseResult<Void> topInformation(@RequestParam Long informationid)
    {
        int i = tbInformationService.topInformation(informationid);
        if (i>0){
            return new ResponseResult<>(HttpStatus.OK.value(),"置顶成功",null);
        }
        else
        {
            return new ResponseResult<>(HttpStatus.BAD_REQUEST.value(),"置顶失败，请重试",null);
        }
    }

}
